package com.soft.mainsite.module.wx.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.PageInfo;
import com.soft.mainsite.common.domain.RestResponse;
import com.soft.mainsite.module.data.dao.UserDataMapper;
import com.soft.mainsite.module.data.dto.DataQueryParams;
import com.soft.mainsite.module.data.dto.UserDataDTO;
import com.soft.mainsite.module.data.entity.MainData;
import com.soft.mainsite.module.data.entity.UserData;
import com.soft.mainsite.module.data.service.DataService;
import com.soft.mainsite.module.wx.config.CacheConfig;
import com.soft.mainsite.module.wx.dao.WxUserMapper;
import com.soft.mainsite.module.wx.entity.WxUser;
import com.soft.mainsite.module.wx.service.WxUserService;
import com.soft.mainsite.module.wx.viewmodel.LoginAuthVm;
import com.soft.mainsite.module.wx.vm.TokenPhoneVM;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author: hjm
 * @Date: 2020/12/4 23:46
 * Stay hungry,stay foolish!
 */
@Slf4j
@Service
@AllArgsConstructor
public class WxUserServiceImpl implements WxUserService {

    private final CacheConfig cacheConfig;

    private static final String CACHE_NAME = "Token";

    private final RedisTemplate redisTemplate;

    @Resource
    private WxUserMapper wxUserMapper;

    @Resource
    private DataService dataService;

    @Resource
    private UserDataMapper userDataMapper;

    @Override
    public RestResponse loginAuth(WxUser wxUser) {

        log.info("微信登录认证请求参数：【{}】", wxUser);
        String openId = wxUser.getOpenId();
        WxUser one = wxUserMapper.getOneByOpenId(openId);
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        log.info("微信登录认证请求时，得到的openId = 【{}】", openId);

        if (one == null) {
            wxUser.setCreateTime(new Date());
            wxUser.setUserState(1);
            wxUserMapper.insertWxUser(wxUser);
        } else {
            wxUser.setUpdateTime(new Date());
            wxUser.setId(one.getId());
            wxUserMapper.updateWxUserById(wxUser);

            wxUser.setPhone(one.getPhone());
        }

        LoginAuthVm loginAuthVm = new LoginAuthVm();
        BeanUtil.copyProperties(wxUser, loginAuthVm);
        loginAuthVm.setToken(token);

        log.info("微信登录认证请求时，返回给前端的用户信息 = 【{}】", loginAuthVm);
        return RestResponse.success(loginAuthVm);
    }

    @Override
    public RestResponse bindPhoneByOpenId(String openId, String phoneNumber) {

        log.info("绑定手机号请求参数 openId = 【{}】, phoneNumber = 【{}】", openId, phoneNumber);

        WxUser one = wxUserMapper.getOneByOpenId(openId);
        one.setPhone(phoneNumber);
        wxUserMapper.updateWxUserById(one);

        // 用户绑定手机号时，先在用户表中查询是否已有领取的资料，如果有，则不需要保存9条数据
        List<UserDataDTO> userDataList = userDataMapper.userDataList(phoneNumber, 0);
        if (userDataList == null || userDataList.size() == 0) {
            this.saveUserDataFirst(phoneNumber);
        }

        String token = UUID.randomUUID().toString().replace("-", "");
        TokenPhoneVM vm = new TokenPhoneVM();
        vm.setToken(token);
        vm.setUserPhone(phoneNumber);

        log.info("绑定手机号请求参数，返回给前端的Token = 【{}】，用户手机号 = 【{}】", token, phoneNumber);

        return RestResponse.success(vm);
    }

    /**
     * 当前用户手机号第一次查询时，如果为空就证明是新的用户，所以先保存默认的9条数据
     *
     * @param userPhone 当前用户手机号
     */
    private void saveUserDataFirst(String userPhone) {

        PageInfo<MainData> pageInfo = dataService.pageDataByConditions(new DataQueryParams(), 1, 9);
        if (pageInfo != null) {
            List<MainData> mainDataList = pageInfo.getList();
            if (mainDataList != null && mainDataList.size() > 0) {
                for (MainData mainData : mainDataList) {
                    UserData userData = new UserData();
                    userData.setUserState(1);
                    userData.setIsFavorite(0);
                    userData.setIsReceived(1);
                    userData.setCreateTime(new Date());
                    userData.setDataId(mainData.getId());
                    userData.setStatus(0);
                    userData.setUserPhone(userPhone);
                    int saveUserData = userDataMapper.saveUserData(userData);
                    if (saveUserData > 0) {
                        log.info("保存当前用户手机号成功！用户手机号：userPhone = 【{}】", userPhone);
                    }else {
                        log.error("保存当前用户手机号失败！用户手机号：userPhone = 【{}】", userPhone);
                    }
                }
            }
        }
    }
}
